package cn.com.callback;
import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import cn.com.elite.Util;

/**
 *
 * @Title: api_m_statisfaction
 * @Description: 华盛证券- 马来海外 提供avaya传递满意度--外部接口
 * @author: qah
 * @date 2020-07-27 10:20:00
 *
 */

public class api_m_statisfaction implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(api_m_statisfaction.class);
	
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		//response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		log.debug("-------------------------start api_m_statisfaction 获取avaya满意度开始-----------------");
		log.debug("request请求----------------:"+request);

		String getMethod = request.getMethod();
		String callJson="";
		BufferedReader iny = null;
		
		log.debug("getMethod:"+getMethod);
		if (getMethod.equals("GET")) {
			callJson = request.getParameter("jsondata");
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				callJson += line;
			}
		}
		
		log.debug("callJson:"+callJson);
		
		String sys_source ="";
		String arr_data ="";
		try {
		// 调用处理信息
		JSONObject inObject = new JSONObject(callJson);
		log.debug("处理前的Json：" + inObject.toString());
			
		sys_source = GetJV(inObject, "sys_source");
		arr_data = GetJV(inObject, "data");
			
		log.debug("解析信息-sys_source：" + sys_source + " arr_data：" + arr_data);
		if(sys_source!='AVAYA'){
			return "{\"resultcode\":\"-1\",\"resultmessage\":\"调用接口返回异常，请检查报文格式！\",\"data\":null}";
		}
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";

		}
		// 调用处理信息
		long startTime = System.currentTimeMillis();
		JSONArray arrJsonArray;
		Map<String, String> dealMap = new HashMap<String, String>();
		Map<String, String> dealMsgMap = new HashMap<String, String>();
		JSONArray resArray = new JSONArray();
		String reJson = null;
		arrJsonArray = new JSONArray(arr_data);
		
		try {
			int arrInt = arrJsonArray.length();
			log.debug("接入List数量:" + arrInt);
			
			for (int i = 0; i < arrInt; i++) {
			JSONObject arrsfJson = arrJsonArray.getJSONObject(i);
			
			//满意度信息
			String ucid = GetJV(arrsfJson, "ucid");
			String customer_number = GetJV(arrsfJson, "customer_number");
			String time = GetJV(arrsfJson, "time");
			String option1 = GetJV(arrsfJson, "option1");
			String option2 = GetJV(arrsfJson, "option2");
			
			log.debug("解析信息-ucid：" + ucid + " customer_number：" + customer_number+ " time：" + time+ " option1：" + option1+ " option2：" + option2);

			//处理
			String dealResult = "";
			String dealMessage = "";
			if(isNull(ucid)||isNull(time)||isNull(customer_number)) {
				dealResult = "0";
				dealMessage = isNullMSG("ucid", ucid) + isNullMSG("time", time) + isNullMSG("customer_number", customer_number) ;
			}else {
					try {
					//判断推送数据是否存在
					def countNum = eliteBean.chaxun_sql("select count(*) as Count from wmsk_statisfaction where uui='" + ucid + "'",'dataSource');
					def Countnumj =countNum.get(0).get("Count");
					log.debug("判断通话唯一标识是否重复:"+Countnumj);
					if(Countnumj<=0) {
						def updateSQL="insert into  wmsk_statisfaction (STATISFACTION_GUID,statisfaction1,statisfaction2,time,uui,PHONENO) values(UUID(),'" + option1+ "','" + option2+ "','" + time+ "','" + ucid+ "','" + customer_number+ "')";
						dealResult=eliteBean.update(updateSQL,"dataSource");
						log.debug("当前满意度数据成功写入数据库！"+dealResult);
					}else {
						def updateSQL="update WMSK_Statisfaction set statisfaction1='" + option1+ "',statisfaction2='" + option2+ "',time='" + time+ "',PHONENO='" + customer_number+ "' where uui='" + ucid + "'";
						dealResult=eliteBean.update(updateSQL,"dataSource");
						log.debug("当前数据推送重复,执行更新操作！"+dealResult)
					}

						} catch (Exception e) {
							dealResult = "0";
							dealMessage = "当前满意度执行更新结果SQL异常";
							log.error(dealMessage + ":" + e.getMessage());
						}
			}

			log.debug("当前ucid:" + ucid + " 处理结果Code:" + dealResult + " 处理结果Message:" + dealMessage);
			dealMap.put(ucid, dealResult);
			dealMsgMap.put(ucid, dealMessage);
			}
			int j = 0;
			for (Map.Entry<String, String> m : dealMap.entrySet()) {
				JSONObject resObject = new JSONObject();
				resObject.put("id", m.getKey());
				resObject.put("code", "1");
				//resObject.put("message", dealMsgMap.get(m.getKey()).toString());
				resArray.put(j, resObject);
				j++;
			}

			//生成处理完成时间
			long endTime = System.currentTimeMillis();

			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";
			log.debug("返回Json:"+reJson);
			return reJson;
		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
			log.debug("处理异常返回Json:"+reJson);
			return reJson;
		}

	}
	
	
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}
	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}
}
